package org.mushroomdb.parser.sql92.impl.util;

import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.NoSuchElementException;

import org.mushroomdb.catalog.Column;
import org.mushroomdb.catalog.EncodeableRegister;
import org.mushroomdb.catalog.Register;
import org.mushroomdb.catalog.Table;

/**
 * Objeto definido en runtime que puede ser tratado como tabla.
 * Para ser usado por el parser.
 * @author Admin
 *
 */
public class TableExpression implements Table {

	private Collection crossProductTableCollection;
	
	public TableExpression(Collection tables) {
			this.crossProductTableCollection = tables;
	}

	public String getName() {
		return "";
	}

	public void setName(String name) {
		//do nothing
	}

	public Iterator getColumns() {
		return new Iterator() {

			private Iterator internalIterator = TableExpression.this.crossProductTableCollection.iterator();
			private Iterator currentTableIterator;
			
			public void remove() {
				throw new UnsupportedOperationException();
			}
			
			private boolean changeIterator() {
				if (this.internalIterator.hasNext()) {
					this.currentTableIterator = ((Table)this.internalIterator.next()).getColumns();
					return true;
				}
				else {
					this.currentTableIterator = (new LinkedList()).iterator();
					return false;
				}
			}

			public boolean hasNext() {
				if (this.currentTableIterator == null) {
					changeIterator();
				}
				while (!this.currentTableIterator.hasNext() && changeIterator()) {
					
				}
				return this.currentTableIterator.hasNext();
			}

			public Object next() {
				if (this.hasNext()) return this.currentTableIterator.next();
				else throw new NoSuchElementException();
			}
			
		};

	}

	public void addColumn(Column column) {
		//do nothing
	}

	public Column getColumn(String name) {
		Iterator iterator = this.getColumns();
		while (iterator.hasNext()) {
			Column column = (Column)iterator.next();
			if (column.getName().equals(name)) return column;
		}
		return null;
	}

	public Iterator getRegisters() {
		return (new LinkedList()).iterator();
	}

	public Iterator getPages() {
		return (new LinkedList()).iterator();
	}

	public void insertRegister(EncodeableRegister register) {
		//do nothing
	}

	public boolean deleteRegister(Register register) {
		//do nothing
		return false;
	}

	public long getRegisterCount() {
		return 0;
	}

}
